package com.demo.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.common.Result;
import com.demo.common.utils.JWTUtils;
import com.demo.entity.Administrator;
import com.demo.mapper.AdministratorMapper;
import com.demo.vo.LoginVO;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户表
 */

@RestController
@RequestMapping("/user")
public class AdministratorController {
  @Resource
  AdministratorMapper administratorMapper;
  
  //  登录验证
  @PostMapping("/login")
/**
 * LoginVO 只有 username 和 password 两个参数
 */
  public Result<?> login(@RequestBody LoginVO user) {
    
    //比较输入的用户名和密码与数据库中的用户名和密码
    Administrator res = administratorMapper.selectOne(Wrappers.<Administrator>lambdaQuery().eq(Administrator::getUsername, user.getUsername()).eq(Administrator::getPassword, user.getPassword()));
    if (res == null) {
      return Result.error("-1", "用户名或密码错误");
    }
    try {
      //添加payload载荷
      Map<String, String> map = new HashMap<>();
      map.put("UserName", res.getUsername());
      map.put("id", String.valueOf(res.getId()));
      map.put("sign", res.getSign());
      //生成token
      String token = JWTUtils.getToken(map);
      /*//将token作为一个map传入data
      Map<String, String> tokenRes = new HashMap<>();
      tokenRes.put("token", token);*/
      res.setToken(token);
      res.setPassword("已加密");
      //向前端返回code状态码msg信息和token
      return Result.success(res);
    } catch (Exception e) {
      //添加载荷失败
      return Result.error("502", e.getMessage());
    }
  }
  
  //  注册,只能管理员携带token注册,不可自主注册
  @PostMapping
  public Result<?> insert(@RequestBody Administrator administrator) {
    administratorMapper.insert(administrator);
    return Result.success();
  }
  
  //  删除 ById
  @DeleteMapping("/{id}")
  public Result<?> delete(@PathVariable Integer id) {
    administratorMapper.deleteById(id);
    return Result.success();
  }
  
  // 修改
  @PutMapping
  public Result<?> updata(@RequestBody Administrator administrator) {
    try {
      administratorMapper.updateById(administrator);
      return Result.success();
    } catch (Exception e) {
      //因为能调用到这个方法,且报错,前端拦截rule不为空,则只有主键重复错误,可以直接拦截提示
      return Result.error("202", "用户名已重复");
    }
  }
  
  /**
   * 分页,默认1页,10个数据,根据userName查询
   *
   * @param pageNum  页数
   * @param pageSize 页面显示数
   * @param search   搜索关键字
   * @return
   */
  @GetMapping
  public Result<?> findPageByUserName(@RequestParam(defaultValue = "1") Integer pageNum,
                                      @RequestParam(defaultValue = "10") Integer pageSize,
                                      @RequestParam(defaultValue = "") String search) {
    LambdaQueryWrapper<Administrator> wrapper = Wrappers.<Administrator>lambdaQuery();
    //根据Id逆序排列
    wrapper.orderByDesc(Administrator::getId);
    if (StrUtil.isNotBlank(search)) {
      wrapper.like(Administrator::getUsername, search);
    }
    
    Page<Administrator> AdminPage = administratorMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
    return Result.success(AdminPage);
  }
  
  @GetMapping("/{id}")
  public Result<?> getById(@PathVariable Integer id) {
    return Result.success(administratorMapper.selectById(id));
  }
  
  

  
/*  //取出token值
  @PostMapping("/test")
  public String test(HttpServletRequest request){
    String token = request.getHeader("token");
    DecodedJWT verify = JWTUtils.verify(token);
    //获取id
    String id = verify.getClaim("id").asString();
    return id;
  }
  */
}
